package com.investment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.investment.model.entity.Factor;
import com.investment.repository.FactorRepository;
import com.investment.service.FactorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 因子服务实现类
 */
@Service
public class FactorServiceImpl implements FactorService {

    @Autowired
    private FactorRepository factorRepository;

    @Override
    public IPage<Factor> listByPage(Map<String, Object> params, Integer page, Integer size) {
        QueryWrapper<Factor> queryWrapper = new QueryWrapper<>();
        
        // 添加查询条件
        if (params != null) {
            // 因子名称
            if (params.containsKey("name") && StringUtils.hasText((String) params.get("name"))) {
                queryWrapper.like("name", params.get("name"));
            }
            
            // 因子代码
            if (params.containsKey("code") && StringUtils.hasText((String) params.get("code"))) {
                queryWrapper.like("code", params.get("code"));
            }
            
            // 因子类型
            if (params.containsKey("type") && params.get("type") != null) {
                queryWrapper.eq("type", params.get("type"));
            }
            
            // 创建者ID
            if (params.containsKey("creatorId") && params.get("creatorId") != null) {
                queryWrapper.eq("creator_id", params.get("creatorId"));
            }
            
            // 状态
            if (params.containsKey("status") && params.get("status") != null) {
                queryWrapper.eq("status", params.get("status"));
            }
        }
        
        // 排序
        queryWrapper.orderByDesc("create_time");
        
        // 分页查询
        Page<Factor> pageParam = new Page<>(page, size);
        return factorRepository.selectPage(pageParam, queryWrapper);
    }

    @Override
    public Factor getByCode(String code) {
        // 尝试使用自定义的selectByCode方法
        try {
            return factorRepository.selectByCode(code);
        } catch (Exception e) {
            // 如果自定义方法有问题，使用基础查询
            QueryWrapper<Factor> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("code", code);
            return factorRepository.selectOne(queryWrapper);
        }
    }

    @Override
    public Factor getById(Long id) {
        return factorRepository.selectById(id);
    }

    @Override
    public Map<String, Object> getFactorDetail(Long id) {
        Map<String, Object> result = new HashMap<>();
        
        // 尝试使用自定义的selectWithDetail方法
        try {
            Map<String, Object> detailMap = factorRepository.selectWithDetail(id);
            if (detailMap != null && !detailMap.isEmpty()) {
                return detailMap;
            }
        } catch (Exception e) {
            // 如果自定义方法有问题，使用基础查询
        }
        
        // 基础查询
        Factor factor = factorRepository.selectById(id);
        if (factor == null) {
            return result;
        }
        
        result.put("factor", factor);
        
        return result;
    }

    @Override
    @Transactional
    public Long addFactor(Factor factor) {
        if (factor == null) {
            return null;
        }
        
        // 设置默认状态
        if (factor.getStatus() == null) {
            factor.setStatus(0);
        }
        
        // 设置创建和更新时间
        Date now = new Date();
        factor.setCreateTime(now);
        factor.setUpdateTime(now);
        
        // 尝试使用自定义的insertFactor方法
        try {
            factorRepository.insertFactor(factor);
        } catch (Exception e) {
            // 如果自定义方法有问题，使用基础插入
            factorRepository.insert(factor);
        }
        
        return factor.getId();
    }

    @Override
    @Transactional
    public boolean updateFactor(Factor factor) {
        if (factor == null || factor.getId() == null) {
            return false;
        }
        
        // 设置更新时间
        factor.setUpdateTime(new Date());
        
        // 尝试使用自定义的updateFactor方法
        try {
            int result = factorRepository.updateFactor(factor);
            return result > 0;
        } catch (Exception e) {
            // 如果自定义方法有问题，使用基础更新
            int result = factorRepository.updateById(factor);
            return result > 0;
        }
    }

    @Override
    @Transactional
    public boolean deleteFactor(Long id) {
        if (id == null) {
            return false;
        }
        
        // 尝试使用自定义的deleteFactor方法
        try {
            int result = factorRepository.deleteFactor(id);
            return result > 0;
        } catch (Exception e) {
            // 如果自定义方法有问题，使用基础删除
            int result = factorRepository.deleteById(id);
            return result > 0;
        }
    }

    @Override
    @Transactional
    public boolean batchDeleteFactor(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            return false;
        }
        
        int result = factorRepository.deleteBatchIds(ids);
        return result > 0;
    }

    @Override
    public List<Factor> listByType(Integer type) {
        if (type == null) {
            return Collections.emptyList();
        }
        
        QueryWrapper<Factor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        queryWrapper.eq("status", 0); // 只查询启用状态的因子
        queryWrapper.orderByDesc("create_time");
        
        return factorRepository.selectList(queryWrapper);
    }

    @Override
    public List<Factor> listByCreatorId(Long creatorId) {
        if (creatorId == null) {
            return Collections.emptyList();
        }
        
        QueryWrapper<Factor> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("creator_id", creatorId);
        queryWrapper.orderByDesc("create_time");
        
        return factorRepository.selectList(queryWrapper);
    }
} 